<template>
  <div class="year-range-picker">
    <px-date-picker
      v-model="startYear"
      type="year"
      :placeholder="`开始年份`"
      size="mini"
      class="year-picker"
      style="max-width: 150px !important"
      format="YYYY"
      value-format="YYYY"
      @change="changeStartYear"
    />
    <span class="range-word"> - </span>
    <px-date-picker
      v-model="endYear"
      type="year"
      :placeholder="`结束年份`"
      size="mini"
      class="year-picker"
      style="max-width: 150px !important"
      format="YYYY"
      value-format="YYYY"
      @change="changeEndYear"
    />
  </div>
</template>

<script setup lang="ts">
import { PxMessage } from "px-ui";
import { ref, watchEffect } from "vue";

const props = {
  yearRange: {
    type: Array,
    default: []
  }
};

//绑定年份
const startYear = ref("");
const endYear = ref("");
const emits = defineEmits(["yearChanged"]);
watchEffect(() => {
  startYear.value = String(props.yearRange[0]);
  endYear.value = String(props.yearRange[1]);
});

const changeStartYear = val => {
  if (Number(val) && Number(endYear.value) && Number(startYear.value) > Number(endYear.value)) {
    startYear.value = "";
    // return   PxMessage.error("")
  }
  if (val) {
    startYear.value = val;
  }
  let times = [Number(startYear.value) || "", Number(endYear.value) || ""];

  // 将改动传回父组件
  emits("yearChanged", times);
};
const changeEndYear = val => {
  if (Number(val) && Number(startYear.value) && Number(startYear.value) > Number(endYear.value)) {
    endYear.value = "";
    // return   PxMessage.error("")
  }

  if (val) {
    endYear.value = val;
  }
  let times = [Number(startYear.value) || "", Number(endYear.value) || ""];

  emits("yearChanged", times);
};
</script>

<style scoped lang="scss">
.year-range-picker {
  font-size: 18px;
  color: black;
  text-align: center;
}

.range-word {
  margin-right: 10px;
  margin-left: 10px;
}

.year-picker {
  max-width: 100px !important;
}
</style>
